package NG::Sys::Cached::DBColumnMulti;
use strict;
use warnings;
use utf8;

use base 'NG::Sys::Cached::Base';

sub init {
	my ($self) = @_;
	$self->SUPER::init;
	unless($self->{table}){
		die "need table\n";
	}
	unless($self->{pkey}){
		die "need pkey\n";
	}
	unless($self->{nkey}){
		die "need nkey\n";
	}
	unless($self->{vkey}){
		die "need vkey\n";
	}
	unless(UNIVERSAL::isa($self->{vkey},"ARRAY")){
		die "vkey must be arrayref\n";
	}
	if($self->{hash_fields}{$self->{pkey}}){
		die $self->{pkey}." present in fields\n";
	}
	unless($self->{dbh}){
		die "need dbh";
	}
	$self->{sth}{read} = $self->{dbh}->prepare(
			"select `".$self->{nkey}."`,".join(",",map {"`".$_."`"} @{$self->{vkey}})." from `".$self->{table}."` where `".$self->{pkey}."`=?");
	$self->{sth}{update} = $self->{dbh}->prepare(
			"replace `".$self->{table}."` (`".$self->{pkey}."`,`".$self->{nkey}."`,".
					join(",",map {"`".$_."`"} @{$self->{vkey}}).
					") values (?,?,".
					join(",", ("?") x @{$self->{vkey}}).
					")");
	$self->{sth}{remove} = $self->{dbh}->prepare(
			"delete from `".$self->{table}."` where `".$self->{pkey}."`=?");
}
sub _remove_source {
	my ($self,$id) = @_;
	my $sth = $self->{sth}{remove};
	$sth->execute($id);
}
sub _read_source {
	my ($self,$id) = @_;
	my $sth = $self->{sth}{read};
	$sth->execute($id);
	my $ary = $sth->fetchall_arrayref;
	my %data;
	for my $row(@$ary){
		my $k = shift @$row;
		$data{$k} = $row;
	}
	return \%data;
}
sub _replace_source {
	goto &_update_source;
}
sub _update_source {
	my ($self,$id,$data,$keys) = @_;
	unless($keys or @$keys){
		return 0;
	}
	my $sth = $self->{sth}{update};
	for my $key(@$keys){
		$sth->execute($id,$key,@{$data->{$key}});
	}
	return $keys;
}


1;
